/******************************  ******************************/
$(function(){
    gridInit02();
    gridInit03();
    gridInit04();
    gridInit0m();
    clickTr();
    $('li[data-opt="back"]').on('click', back);
    $('.modal-data').draggable({cancel:'.u_modal_body, input'});
    myModal.find('.u_title.u_close').on('click', function(){    //关闭模态框
        myModal.addClass('hidden');
        //gridInit02();
    });
    $('li[data-opt="add"]').on('click', function(){ //添加
        window.open('MDM003502.html', '_blank');
    });
    $('li[data-opt="u_save"],button[data-opt="u_save"]').on('click', function(){    //保存
        console.log('您按了保存按钮');
        var MDM003502 = [], _MDM003503 = [], _MDM003504 = [];
        //console.log(Data02)
        Data02.forEach(function(v,i,a){
            console.log(v)
            MDM003502.push({"Code":idx[1],"LineID":i+1,"OrderById":i+1,"CategoryCode":v.CategoryCode,"CategoryName":v.CategoryName,"ShowName":v.ShowName,"Picture_PC_Code":"string","Picture_PC_Address":v.Picture_PC_Address});
        });
        Data03.forEach(function(v,i,a){
            _MDM003503.push({"Code":idx[1],"LineID":i+1,"OrderById":"","CategoryCode":v.CategoryCode,"CategoryName":v.CategoryName,"ShowName":v.ShowName,"Father":v.Father});
        });
        Data04.forEach(function(v,i,a){
            //console.log(v)
            _MDM003504.push({"Code":idx[1],"LineID":i+1,"OrderById":"","SKU":v.SKU,"ItemName":v.ItemName,"Father":v.Father});
        });
        for(var i=0,MDM003503=[];i<_MDM003503.length;i++){
            MDM003503.push(_MDM003503[i]);
            for(var j=0,flag=1;j<MDM003503.length-1;j++){
                _MDM003503[i].Father==MDM003503[j].Father&&flag++;
            }
            MDM003503[i].OrderById = flag;
        }
        for(var i=0,MDM003504=[];i<_MDM003504.length;i++){
            MDM003504.push(_MDM003504[i]);
            for(var j=0,flag=1;j<MDM003504.length-1;j++){
                _MDM003504[i].Father==MDM003504[j].Father&&flag++;
            }
            MDM003504[i].OrderById = flag;
        }
        console.log(MDM003502);
        console.log(MDM003503);
        console.log(MDM003504);
        var requestData = Object.create(postData);
        requestData.Method = 'U';
        requestData.Content = {
            Code: idx[1],
            Name: $('#ItemName').val(),
            MDM003502: MDM003502,
            MDM003503: MDM003503,
            MDM003504: MDM003504,
            MDM003505: MDM003505,
            MDM003506: MDM003506
        };
        console.log(requestData)
        $.ajax({
            type: "post",
            url: mdmPath+'/MDM0035/MDM003501',
            data: requestData,
            dataType: "json",
            success: function (re) {
                if (re.Status == 200) {
                    myAlert('保存成功');
                } else {
                    myAlert(re.Message);
                }
            }
        });
    });
});

//grid表格行数
gridData.rowNum = 1000;

var pattern = new RegExp(/\?Code=(\S*)/g);
var idx = pattern.exec(window.location.href);

var MDM003505 = [], MDM003506 = [];

if (idx) {
    //ajax请求页面数据
    var Data02,Data03,Data04,Father,TempData02=[],TempData03=[],TempData04=[];
    var url = mdmPath + '/MDM0035/MDM003503';   //请求地址
    var _postData = Object.create(postData);    //请求头
    _postData.Method = 'Q';
    _postData.Content = {
        Code: idx[1]
    }
    $.ajax({
        async: false,
        type: "post",
        url: url,
        data: _postData,
        dataType: "json",
        success: function (re) {
            if (re.Status == 200) {
                loadAjax(re);
            } else if (re.Status == -999) {
                alert_QX($('body'), re.Message);
            } else {
                myAlert(re.Message);
            }
        }
    });
    // 模态框表格请求头
    var postData0m = Object.create(postData);
    postData0m.Method = 'Q';
    postData0m.Content = {
        // PCode: idx[1],
        // Level: '2'
    }
}

function loadAjax(re){
    $('#ItemCode').val(re.Content.Code);
    $('#ItemName').val(re.Content.Name);
    Data02 = re.Content.MDM003502;  //console.log(Data02);
    Data03 = re.Content.MDM003503;  //console.log(Data03);
    Data04 = re.Content.MDM003504;  //console.log(Data04);
    MDM003505 = re.Content.MDM003505;
    MDM003506 = re.Content.MDM003506;
    Data02.forEach(function(v,i,a){
        TempData02.push(v);
    });
    TempData02.push({});
}

function alarmFormatter(cellvalue, options, rowdata){
    var grid = $(this);
    if(JSON.stringify(rowdata)!=='{}'){
        cellvalue = '<a href="javascript:0" opt-data="'+grid[0].id+'_edit" title="编辑"><i class="fa fa-pencil"></i></a>'+
            '&nbsp;<a class="hidden" href="javascript:0" opt-data="'+grid[0].id+'_save" title="保存"><i class="fa fa-check"></i></a>'+
            '&nbsp;<a href="javascript:0" opt-data="'+grid[0].id+'_delete" title="删除"><i class="fa fa-trash-o"></i></a>';
    }else{
        cellvalue = '';
    }
    //console.log(cellvalue);
    //console.log(options);
    //console.log(rowdata);
    return cellvalue;
}

function picFormatter(cellvalue, options, rowdata){
    var grid = $(this);
    if(JSON.stringify(rowdata)!=='{}'){
        cellvalue = '';
        if(rowdata.Picture_PC_Address){
            cellvalue += '<img src="'+PicAddress+rowdata.Picture_PC_Address+'">';
        };
        cellvalue += '&nbsp;<a href="javascript:0" opt-data="'+grid[0].id+'_upload" title="上传图片"><i class="fa fa-cloud-upload"></i></a>';
    }else{
        cellvalue = '';
    }
    return cellvalue;
}

function gridInit02(){
    var gridData02 = Object.create(gridData);
    gridData02.grid = $('#jgTable02');
    //gridData02.pager = $('#jgPager02');
    gridData02.datatype = "local";
    gridData02.colModel = [
        {label:'分类代码', name:'CategoryCode', sortable: false},
        {label:'分类名称', name:'CategoryName', sortable: false},
        {label:'分类显示名称', name:'ShowName', editable:true, sortable: false},
        {label:'图片', name:'Picture_PC_Address', formatter: picFormatter, sortable: false},
        {label:'操作', name:'Options', width:80, align:'center', formatter: alarmFormatter, sortable: false}
    ];
    gridData02.beforeRequest = function(){
        gridData02.grid.jqGrid("setGridParam", {
            data : TempData02,
        });
    };
    gridData02.loadComplete = function(xhr){ 
        var rowData = gridData02.grid.jqGrid("getRowData");
        $('a[opt-data="jgTable02_delete"]').unbind('click').bind('click',function(){
            var rowId = $(this).parent().parent()[0].id;
            //console.log(rowId);
            gridData02.grid.jqGrid("delRowData",rowId);
            //console.log(rowData[rowId-1].CategoryCode);
            Data02.forEach(function(v,i,a){
                v.CategoryCode===rowData[rowId-1].CategoryCode&&Data02.splice(i,1);
            });
            TempData02.forEach(function(v,i,a){
                v.CategoryCode===rowData[rowId-1].CategoryCode&&TempData02.splice(i,1);
            });
            //子表03数据删除
            for(var i=0;i<Data03.length;i++){
                if(Data03[i].Father===rowData[rowId-1].CategoryCode){
                    //console.log(i+'删除');
                    Data03.splice(i,1);
                    i--;
                };
            }
            for(var i=0;i<TempData03.length;i++){
                if(TempData03[i].Father===rowData[rowId-1].CategoryCode){
                    //console.log(i+'删除');
                    TempData03.splice(i,1);
                    i--
                };
            }
            $('#jgTable03').jqGrid("clearGridData").trigger("reloadGrid");
            //子表04数据删除
            for(var i=0;i<Data04.length;i++){
                if(Data04[i].Father===rowData[rowId-1].CategoryCode){
                    //console.log(i+'删除');
                    Data04.splice(i,1);
                    i--;
                };
            }
            for(var i=0;i<TempData04.length;i++){
                if(TempData04[i].Father===rowData[rowId-1].CategoryCode){
                    //console.log(i+'删除');
                    TempData04.splice(i,1);
                    i--
                };
            }
            $('#jgTable04').jqGrid("clearGridData").trigger("reloadGrid");
        });
        $('a[opt-data="jgTable02_edit"]').unbind('click').bind('click',function(){
            var rowId = $(this).parent().parent()[0].id;
            gridData02.grid.jqGrid("editRow",rowId);
            $(this).addClass('hidden');
            $(this).next().removeClass('hidden');
        });
        $('a[opt-data="jgTable02_save"]').unbind('click').bind('click',function(){
            var rowId = $(this).parent().parent()[0].id;
            gridData02.grid.jqGrid("saveRow",rowId,false,'clientArray');
            $(this).addClass('hidden');
            $(this).prev().removeClass('hidden');
            var newRowData = gridData02.grid.jqGrid("getRowData",rowId);
            console.log(newRowData.CategoryCode)
            Data02.forEach(function(v,i,a){
                v.CategoryCode===newRowData.CategoryCode&&Data02.splice(i,1,newRowData);
            });
            TempData02.forEach(function(v,i,a){
                v.CategoryCode===newRowData.CategoryCode&&TempData02.splice(i,1,newRowData);
            });
        });
        $('a[opt-data="jgTable02_upload"]').unbind('click').bind('click', function(){
            var td_html = $(this).parent();
            var rowId = $(this).parent().parent()[0].id;
            _this = gridData02.grid.jqGrid("getRowData",rowId).Picture_PC_Address;
            $('#picModal').toggleClass('hidden');
            treePicInit();
            (function addPicSubmit(){  //替换publicModal中的addPicSubmit
                $("#addPicBtn").unbind("click").bind("click",function(){
                    var imgs = $(".u_checked>img");
                    if(imgs.length>0){
                        if(td_html.find('>img').length>0){
                            td_html.find('>img').attr('src', imgs[0].src);
                        }else{
                            td_html.prepend(imgs[0]);
                        };
                        Data02.forEach(function(v,i,a){
                            //console.log(rowId)
                            v.CategoryCode===rowData[rowId-1].CategoryCode&&(v.Picture_PC_Address = imgs[0].src.split(PicAddress)[1]);
                        });
                        TempData02.forEach(function(v,i,a){
                            v.CategoryCode===rowData[rowId-1].CategoryCode&&(v.Picture_PC_Address = imgs[0].src.split(PicAddress)[1]);
                        });
                        myModal.addClass('hidden');
                    }
                });
            })();
        });
    };
    gridData02.onSelectRow = function(rowid,status){
        var strIds = gridData02.grid.jqGrid("getDataIDs");
        if(rowid!=Math.max.apply(null,strIds)){
            var rowData = gridData02.grid.jqGrid('getRowData', rowid);  
            Father = rowData.CategoryCode;  //二级类别的ID即三级类别父级

            $('.ctyTitle').html(rowData.CategoryName+'['+Father+']');

            //console.log(TempData03)
            var _Data03 = [];
            Data03.forEach(function(v,i,a){
                v.Father===Father&&_Data03.push(v);
            });
            _Data03.push({});
            TempData03 = _Data03;
            $('#jgTable03').jqGrid('clearGridData').trigger('reloadGrid');

            var _Data04 = [];
            Data04.forEach(function(v,i,a){
                v.Father===Father&&_Data04.push(v);
            });
            _Data04.push({});
            TempData04 = _Data04;
            $('#jgTable04').jqGrid('clearGridData').trigger('reloadGrid');

        }else{
            console.log('您选中的是最后一行');
        }
    };
    gridData02.ondblClickRow = function(rowid,iRow,iCol,e){
        var _grid = gridData02.grid;
        var strIds = _grid.jqGrid("getDataIDs");	//获得表格所有行的ID
        if(rowid==Math.max.apply(null,strIds)){
            modalInit(_grid);
        }
    };
    gridInit(gridData02);
}

function gridInit03(){
    var gridData03 = Object.create(gridData);
    gridData03.grid = $('#jgTable03');
    //gridData03.pager = $('#jgPager03');
    gridData03.datatype = "local";
    gridData03.colModel = [
        {label:'分类代码', name:'CategoryCode', sortable: false},
        {label:'分类名称', name:'CategoryName', sortable: false},
        {label:'分类显示名称', name:'ShowName', editable:true, sortable: false},
        // {label:'父级代码', name:'Father', sortable: false},
        // {label:'排序行号', name:'OrderById', sortable: false}
        {label:'操作', name:'Options', width:80, align:'center', formatter: alarmFormatter, sortable: false}
    ];
    gridData03.beforeRequest = function(){
        console.log(TempData03);
        gridData03.grid.jqGrid("setGridParam", {
            data : TempData03
        });
    };
    gridData03.loadComplete = function(xhr){
        var strIds = gridData03.grid.jqGrid("getDataIDs");
        var rowData = gridData03.grid.jqGrid("getRowData");
        $('a[opt-data="jgTable03_delete"]').unbind('click').bind('click',function(){
            var rowId = $(this).parent().parent()[0].id;
            gridData03.grid.jqGrid("delRowData",rowId);
            Data03.forEach(function(v,i,a){
                v.CategoryCode===rowData[rowId-1].CategoryCode&&Data03.splice(i,1);
            });
            TempData03.forEach(function(v,i,a){
                v.CategoryCode===rowData[rowId-1].CategoryCode&&TempData03.splice(i,1);
            });
        });
        $('a[opt-data="jgTable03_edit"]').unbind('click').bind('click',function(){
            var rowId = $(this).parent().parent()[0].id;
            gridData03.grid.jqGrid("editRow",rowId);
            $(this).addClass('hidden');
            $(this).next().removeClass('hidden');  
        });
        $('a[opt-data="jgTable03_save"]').unbind('click').bind('click',function(){
            var rowId = $(this).parent().parent()[0].id;
            gridData03.grid.jqGrid("saveRow",rowId,false,'clientArray');
            $(this).addClass('hidden');
            $(this).prev().removeClass('hidden');
            var newRowData = gridData03.grid.jqGrid("getRowData",rowId);
            //console.log(newRowData.CategoryCode);
            newRowData.Father = Father;
            //console.log(newRowData)
            Data03.forEach(function(v,i,a){
                v.CategoryCode===newRowData.CategoryCode&&Data03.splice(i,1,newRowData);
            });
            TempData03.forEach(function(v,i,a){
                v.CategoryCode===newRowData.CategoryCode&&TempData03.splice(i,1,newRowData);
            });
        });
    }
    gridData03.ondblClickRow = function(rowid,iRow,iCol,e){
        var _grid = gridData03.grid;
        var strIds = _grid.jqGrid("getDataIDs");	//获得表格所有行的ID
        if(rowid==Math.max.apply(null,strIds)){
            modalInit(_grid);
        }
    };
    gridInit(gridData03);
}

function gridInit04(){
    var gridData04 = Object.create(gridData);  
    gridData04.grid = $('#jgTable04');  
    gridData04.datatype = "local";
    gridData04.colModel = [
        {label:'代码', name:'SKU', sortable: false},
        {label:'名称', name:'ItemName', sortable: false},
        {label:'操作', name:'Options', width:80, align:'center', formatter: alarmFormatter, sortable: false}
    ];
    gridData04.beforeRequest = function(){
        //console.log(TempData04);
        gridData04.grid.jqGrid("setGridParam", {
            data : TempData04
        });
    };
    gridData04.loadComplete = function(xhr){
        var strIds = gridData04.grid.jqGrid("getDataIDs");
        var rowData = gridData04.grid.jqGrid("getRowData");
        $('a[opt-data="jgTable04_delete"]').unbind('click').bind('click',function(){
            var rowId = $(this).parent().parent()[0].id;
            gridData04.grid.jqGrid("delRowData",rowId);
            Data04.forEach(function(v,i,a){
                v.SKU===rowData[rowId-1].SKU&&Data04.splice(i,1);
            });
            TempData04.forEach(function(v,i,a){
                v.SKU===rowData[rowId-1].SKU&&TempData04.splice(i,1);
            });
        });   
        $('a[opt-data="jgTable04_edit"]').addClass('hidden');
    };
    gridData04.ondblClickRow = function(rowid,iRow,iCol,e){
        var _grid = gridData04.grid;
        var strIds = _grid.jqGrid("getDataIDs");	//获得表格所有行的ID
        if(rowid==Math.max.apply(null,strIds)){
            modalInit(_grid);
        }
    };
    gridInit(gridData04);
}

function gridInit0m(){
    var gridData0m = Object.create(gridData);
    gridData0m.rowNum = 10;
    gridData0m.grid = $('#jgTable0m');
    gridData0m.pager = $('#jgPager0m');
    gridData0m.height = '390px';
    gridData0m.url = mdmPath + '/MDM0003/MDM000304';
    gridData0m.colModel = [
        {label:'代码', name:'Code', sortable:false},
        {label:'名称', name:'Name', sortable:false},
        {label:'图片', name:'IconPath', sortable:false}
    ];
    gridData0m.beforeRequest = function(){
        //console.log(postData)
        //console.log(postData0m) 
        gridData0m.grid.jqGrid("setGridParam", {
            postData : postData0m,
        });
    }
    gridData0m.multiselect = true;
    gridInit(gridData0m);
}

function back(){
    window.open('MDM003501.html', '_self');
}

/******************************  ******************************/
function modalInit(_grid){
    //console.log(Father)
    $('#modal-overlay').removeClass('hidden');
    console.log(_grid[0]==$('#jgTable02')[0])
    switch(_grid[0])
    {
        case $('#jgTable02')[0]:
            //console.log('02');
            postData0m.Content = {
                PCode: idx[1],
                Level: '2'
            }
            //console.log(postData0m);
            $('#jgTable0m').setGridParam(
                {
                    url: mdmPath + '/MDM0003/MDM000304',
                    sortname: ''
                }
            ).jqGrid("clearGridData").trigger("reloadGrid");
        break;
        case $('#jgTable03')[0]:
            //console.log('03');
            postData0m.Content = {
                PCode: Father,
                Level: '3'
            }
            //console.log(postData0m);
            $('#jgTable0m').setGridParam(
                {
                    url: mdmPath + '/MDM0003/MDM000304',
                    sortname: ''
                }
            ).jqGrid("clearGridData").trigger("reloadGrid");
        break;
        case $('#jgTable04')[0]:
            //console.log('04');
            postData0m.Content = {
                Category2: Father,
                Putaway: 'Y',
                SearchText: '',
            }
            //console.log(postData0m);
            $('#jgTable0m').setGridParam(
                {   
                    url: mdmPath + '/MDM0004/MDM000402',
                    sortname: 'Name'
                }
            ).jqGrid("clearGridData").trigger("reloadGrid");
            Search(_grid);
        break;
    }
    
    $('#addBtn').unbind('click').bind('click', function(){
        addSubmit(_grid);
    });
}

/******************************  ******************************/
function addSubmit(_grid){
    var _grid0m = $('#jgTable0m');
    //console.log(_grid);
    var rowIds = _grid0m.jqGrid('getGridParam', 'selarrrow');
    for(var arr=[],i=0;i<rowIds.length;i++){
        var _gridData= _grid0m.jqGrid("getRowData",rowIds[i]);	//这是获得 某一行的数据
        // var strValue= grid.jqGrid("getCell",rowIds[i],"Code");	//获得单元格的值
        arr.push(_gridData);
    }
    var newArr = [];
    
    switch(_grid[0])
    {
        case $('#jgTable02')[0]:
            arr.forEach(function(v,i,a){
                newArr.push({"CategoryCode":v.Code,"CategoryName":v.Name,"ShowName":v.Name})
            });
            //console.log(newArr);
            /*****更新Data02*****/
            TempData02.length = TempData02.length-1;
            //console.log(Data02);
            Array.prototype.push.apply(TempData02,newArr);
            //去重
            TempData02 = TempData02.unique('CategoryCode');
            TempData02.push({});
            //console.log(Data02);
            //更新Data02
            Array.prototype.push.apply(Data02,newArr);
            Data02 = Data02.unique('CategoryCode');
            //console.log(Data02);
        break;
        case $('#jgTable03')[0]:
            arr.forEach(function(v,i,a){
                newArr.push({"CategoryCode":v.Code,"CategoryName":v.Name,"ShowName":v.Name,"Father":Father})
            });
            //console.log(newArr);
            /*****更新TempData03*****/
            TempData03.length = TempData03.length-1;
            //console.log(TempData03);
            Array.prototype.push.apply(TempData03,newArr);
            //去重
            TempData03 = TempData03.unique('CategoryCode');
            TempData03.push({});
            console.log(TempData03);
            //更新Data03
            Array.prototype.push.apply(Data03,newArr);
            Data03 = Data03.unique('CategoryCode');
            //console.log(Data03);
        break;
        case $('#jgTable04')[0]:
            arr.forEach(function(v,i,a){
                //console.log(v.Code)
                newArr.push({"SKU":v.Code,"ItemName":v.Name,"Father":Father});
            });
            /*****更新TempData04*****/
            TempData04.length = TempData04.length-1;
            //console.log(TempData04);
            //console.log(newArr)
            Array.prototype.push.apply(TempData04,newArr);
            //console.log(TempData04);
            //去重
            TempData04 = TempData04.unique('SKU');
            TempData04.push({});
            //console.log(TempData04);
            //更新Data04
            Array.prototype.push.apply(Data04,newArr);
            Data04 = Data04.unique('SKU');
            //console.log(Data04);
        break;
    }
    //reload表格
    _grid.jqGrid("clearGridData").trigger("reloadGrid");
    //关闭模态框
    myModal.addClass('hidden');
}

function Search(_grid){
    $("li[data-opt='opt_search']").find(">.fa-search").unbind('click').bind('click', function(){
        console.log('搜索')
        var Category3 = $('input[data-id="Category3"]').val();
        var Code = $('input[data-id="Code"]').val();
        var ProductName = $('input[data-id="ProductName"]').val();
        switch(_grid[0])
        {
            case $('#jgTable02')[0]:
            break;
            case $('#jgTable03')[0]:
            break;
            case $('#jgTable04')[0]:
                postData0m.Content = {
                    Putaway: 'Y',
                    Category2: Father,
                    Category3: Category3,
                    Code: Code,
                    SearchText: ProductName
                }
                $('#jgTable0m').jqGrid("clearGridData").trigger("reloadGrid");
            break;
        }
    });
}

//样式
var gridWidth02 = $('.u_contents');
var gridWidth03 = $('.u_contents');
var gridWidth04 = $('.u_contents');
var gridWidth0m = $('.u_modal_body');
function gridSize(){
    $('#jgTable02').setGridWidth(gridWidth02.width());
    $('#jgTable03').setGridWidth(gridWidth03.width());
    $('#jgTable04').setGridWidth(gridWidth04.width());
    $('#jgTable0m').setGridWidth(gridWidth0m.width());
}

function clickTr(){
    $('#jgTable02').find('>tbody>tr:nth-child(2)').trigger('click');
}




